package cn.shop.merchant.controller.record;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.merchant.req.FkNotifyReq;
import cn.shop.merchant.req.NotifyReq;
import cn.shop.merchant.req.RechargeRecordQueryReq;
import cn.shop.merchant.service.MerchantUserService;
import cn.shop.merchant.service.PromotionsService;
import cn.shop.merchant.service.RechargeRecordService;
import cn.shop.transcation.TransactionRecord.entity.RechargeInfoReq;
import cn.shop.transcation.backPaymentChannelModule.entity.BackPaymentChannel;
import cn.shop.transcation.merchantUser.mapper.entity.MerchantUser;
import cn.shop.transcation.promotionsModule.Promotions;
import cn.shop.utils.ApiResult;
import cn.shop.utils.Putif;
import cn.shop.utils.constant.PromotionsConstant;
import cn.shop.utils.exception.ServiceException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.shop.utils.constant.Constant.UID;

/**
 * 充值相关接口
 *
 * @author : 李一涵
 * @date : Created in 2021-11-10 10:58
 * @description : 充值记录controller
 */
@Slf4j
@RestController
@RequestMapping("/recharge")
public class RechargeRecordController {

    @Resource
    private RechargeRecordService recordService;
    @Resource
    private MerchantUserService userService;
    @Resource
    private PromotionsService promotionsService;

    /**
     * 获取充值记录列表
     *
     * @param req 查询条件
     */
    @GetMapping("/record/list")
    public ApiResult<Map<String, Object>> list(RechargeRecordQueryReq req) {
        long uid = StpUtil.getSession().getLong(UID);
        if (uid == 0) {
            return ApiResult.fail("请检查登录状态");
        }
        Map<String, Object> data = recordService.records(uid, req);
        return ApiResult.success(data);
    }

    /**
     * 获取活动信息
     *
     * @return 返回结果
     */
    @GetMapping("/prize")
    public ApiResult<Map<String, Object>> prizePool() {
        Promotions promotions = promotionsService.getOne(Wrappers.<Promotions>lambdaQuery()
                .eq(Promotions::getKey, PromotionsConstant.PRIZE_POOL));
        if (promotions == null) {
            return ApiResult.success();
        }
        return ApiResult.success(Putif.start()
                .anyway("prize", promotions.getPrizePool())
                .anyway("enable", promotions.getEnable())
                .anyway("content", promotions.getContent())
                .get());
    }

    /**
     * 获取支付通道
     *
     * @return 返回结果
     */
    @GetMapping("/channel")
    public ApiResult<List<Map<String, Object>>> channelList() {
        List<BackPaymentChannel> channels = recordService.channelList();
        return ApiResult.success(channels.stream()
                .map(c -> Putif.start()
                        .anyway("id", c.getId())
                        .anyway("name", c.getName())
                        .anyway("type", c.getType())
                        .anyway("rate", c.getRate())
                        .get())
                .collect(Collectors.toList()));
    }

    /**
     * 充值
     *
     * @param rechargeInfoReq 实体对象
     * @return 新增结果
     * @author lyh
     * @since 2021-12-13 10:49:40
     */
    @PostMapping("recharge")
    public ApiResult<Object> recharge(@Validated @RequestBody RechargeInfoReq rechargeInfoReq, HttpServletRequest request) {
        long uid = StpUtil.getSession().getLong(UID);
        checkIsCertification(uid);
        return ApiResult.success(recordService.recharge(uid, rechargeInfoReq, request));
    }

    /**
     * 支付回调接口
     *
     * @param payCallback
     * @return
     */
    @PostMapping("/notify")
    public String notify(NotifyReq payCallback) {
        log.info("充值回调接受结果：{}", payCallback);
        String notify = recordService.notify(payCallback);
        log.info("充值回调返回：{}", notify);
        return notify;
    }

    /**
     * fk支付回调接口
     *
     * @param payCallback
     * @return
     */
    @PostMapping("/fknotify")
    public String fkNotify(@RequestBody FkNotifyReq payCallback) {
        log.info("充值回调接受结果：{}", payCallback);
        String notify = recordService.fkNotify(payCallback);
        log.info("充值回调返回：{}", notify);
        return notify;
    }

    private void checkIsCertification(long userId) {
        MerchantUser user = userService.getById(userId);
        if (user == null || StrUtil.isBlank(user.getIdentityCard()) || StrUtil.isBlank(user.getPhone())) {
            throw new ServiceException("请先进行实名认证");
        }
        if (StrUtil.isBlank(user.getPhone())) {
            throw new ServiceException("请完善手机号");
        }
    }

}
